<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/12
 * Time: 11:38
 */
/**
 * @author zheng
 * @date 2018/04/12
 * 微信支付操作
 */
namespace app\wechar\service;
use think\Db;
class WxpayService{
    protected  $openid;
    protected  $total_fee;
    protected  $trade_id ;
    protected  $mch_id;
    protected  $key;
    protected  $appid;
    protected  $url;
    protected  $name;

    function  __construct( $openid='',$total_fee='',$trade_id='',$wxappid ='')
    {
        if($wxappid == 2){
            $this->appid = 'wx79ea3f9c1942420d';
            $this->mch_id = '1502247261';   //商户号
            $this->key = 'mqMm5r3gjB5R6Te0PneBTUNWETG7pSPh';   //商户秘钥
            $this->openid = $openid;
            $this->total_fee = $total_fee;
            $this->trade_id = $trade_id;
            $this ->name ="武汉天雅中医院";
            $this -> url ='https://'.$_SERVER['HTTP_HOST'].'/portal/Wechat/Callback'; //回调
        }
        if($wxappid == 1){
            $this->appid = 'wxf3c8fe48a2b6c4a5';
            $this->mch_id = '1503270951';   //商户号
            $this->key = 'HXBh1IN4m0olcXxK4kC2Yn1yvRuK7piD';   //商户秘钥
            $this->openid = $openid;
            $this->total_fee = $total_fee;
            $this->trade_id = $trade_id;
            $this ->name ="武汉天一中医院";
            $this -> url ='https://'.$_SERVER['HTTP_HOST'].'/wechar/Wechat/Callback'; //回调
        }
    }

    /**
     * @author zheng
     * @date zheng
     * 下单api
     */
    function wxpay(){
        $wxorder = $this->getorder();
        $wxorder =  json_decode( json_encode( $wxorder),true);

        if($wxorder['return_code'] == 'FAIL'){
            return json(['message'=>'获取失败','status'=>'0']);
        }

        $pay = array(
            'appId' => $this->appid,//小程序ID
            'timeStamp' =>time(),
            'nonceStr' =>$this ->nonce_str(),
            'package' =>'prepay_id='.$wxorder['prepay_id'],
            'signType' =>'MD5',
        );
        $pay['paySign'] = $this->getsings($pay);
       // $pay['package']="prepay_id={$pay['package']}";
         return json($pay);
    }
    /**
     * @author zheng
     * @date zheng
     * 拼凑下单参数
     */
    protected function getorder(){

        $array = array(
            'appid' => $this ->appid,                                  //appid
            'mch_id' => $this->mch_id,                                 //商户号
            'nonce_str' => $this->nonce_str(),                         //随机字符串
            'body' => $this->name,
            'out_trade_no' => $this ->trade_id,                        //商户单号
            'total_fee' => floatval($this->total_fee * 100),
            'spbill_create_ip' =>get_client_ip(),                      //ip
            'notify_url' => $this -> url,
            'trade_type' =>'JSAPI',                                    //类型
            'openid' =>$this-> openid                                  //openid
        );
        $sign = $this->getsings($array);
        $array['sign'] = $sign;
        $arrayxml = $this -> arrayXml($array);
        $addorder = $this ->PostCurl('https://api.mch.weixin.qq.com/pay/unifiedorder',$arrayxml);
        $string_array = $this ->xmltoarray($addorder);
        return $string_array;

    }
    /**
     * @author zheng
     * @date zheng
     * nonce_str随机字符串参数
     */
    public function nonce_str(){
        $nonce_str ='';
        $code = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        for($i=1; $i<=24; $i++){
            $nonce_str .= $code[rand(0,strlen($code)-1)];
        }
        return $nonce_str;
    }
    /**@author zheng
     * @date 2018/04/28
     * 4次签名
     */
    public function getsings($array){
        //链接值
        $sign = $this ->keyvalue($array);
        //拼凑值
        $sign = $sign.'&key'.'='.$this->key;
        //md5
        $sign =md5($sign);
        //大写
        $sign =strtoupper($sign);
        return $sign;
    }
    /**
     * @author zheng
     * @date 2018/04/12
     * 转键值对应
     */
    public function keyvalue($array){
        //字典序
        ksort($array);
        $res = '';
        //链接
        foreach($array as $key =>$val){
            $res .=$key.'='.$val.'&';
        }
        $res = substr($res,0,strlen($res)-1);
        return $res;
    }
    /**
     * @author zheng
     * @date 2018/04/12
     * xml转换
     */
    public  function arrayXml($array){
        $xml = '';
        $xml .="<xml>";
        foreach($array as $key => $val){
            if(is_numeric($val)) {
                $xml .= "<$key>" . $val . "</$key>";
            }
            else{
                $xml .= "<$key>" ."<![CDATA[".$val."]]>" . "</$key>";
            }

        }
        $xml .="</xml>";
        return $xml;
    }
    /**
     * @author zheng
     * @date 2018/04/13
     * 下单curl
     */
    public  function PostCurl($url,$strData,$second=30){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $strData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //跳过ssl检查
        $output =  curl_exec($ch);
        $info = curl_getinfo($ch);
        if($output === false) {
            $output = "No cURL data returned for $url [". $info['http_code']. "]";
            if (curl_error($ch)){
                $output .= "\n". curl_error($ch);
            }
        }
        curl_close($ch);
        return $output;
    }
    /**
     * @author zheng
     * @date 2018/04/13
     * xml ->数组
     */
    public function xmltoarray($xml){
        libxml_disable_entity_loader(true);
        $string_array = json_decode(json_encode(simplexml_load_string($xml ,'SimpleXMLElement', LIBXML_NOCDATA),true));

        return $string_array;
    }

}